package com.um.springboot.starter.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.um.springboot.starter.constants.SmsConsts;
import com.um.springboot.starter.properties.ThaiBulkSmsProperties;
import com.um.springboot.starter.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;

/**
 * ThaiBulk SMS
 * https://accessyou.com/index.php
 */
@Slf4j
@Component(SmsConsts.THAI_BULK_IMPL)
public class ThaiBulkSmsServiceImpl implements SmsService {

    @Autowired
    ThaiBulkSmsProperties thaiBulkSmsProperties;

    /**
     * 发送短信
     *
     * @param mobileAreaCode 国家代码
     * @param mobile         手机号
     * @param template       模板
     * @param params         模板参数
     * @param customSmsProps 自定义配置
     * @return 是否成功
     */
    @Override
    public boolean send(String mobileAreaCode, String mobile, String template, LinkedHashMap<String, String> params, Object customSmsProps) {
        ThaiBulkSmsProperties props = ObjectUtil.defaultIfNull((ThaiBulkSmsProperties) customSmsProps, this.thaiBulkSmsProperties);

        String phone = mobileAreaCode + mobile;
        String message = StrUtil.format(props.getTemplates().get(template), params.values());
        String body = HttpUtil.createPost("https://api-v2.thaibulksms.com/sms")
                .form("sender", props.getSender())
                .form("msisdn", phone)
                .form("message", message)
                .header("authorization", StrUtil.format("Basic {}", Base64.encode(StrUtil.format("{}:{}",
                        props.getApiKey(), props.getApiSecret()))))
                .setConnectionTimeout(300000)
                .timeout(300000)
                .setReadTimeout(300000)
                .execute()
                .body();
        log.info("【ThaiBulk】短信发送 \n电话：{} \n短信内容：{} \n发送结果：{}", phone, message, body);
        return true;
    }

}
